package 数组.搜索插入位置;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/5/22 21:51
 * @description: 在有序数组中搜索插入位置  O(log n)
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int[] array = {1,3,5,6};
        System.out.println(searchInsert(array, 2));
    }

    //二分法
    public static int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (right - left) / 2;
            if (target < nums[mid]) {
                right = mid - 1;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return left;
    }
}
